<template>
  <Table
    ref="tableRef"
    :columns="columns"
    :data="loadData"
    :alert="false"
    bordered
    :row-key="(record: any) => record.id"
  >
    <template #operator>
      <div class="table-search">
        <div>
          <span class="table-search-box">
            名称：
            <a-input
              v-model:value="searchValue"
              placeholder="请输入交付空间名称/空间编码/命名空间"
              style="width: 240px"
              allowClear
            >
              <template #prefix>
                <SvgIcon class="iconDef" :name="'search'" :color="'#d9d9d9'" width="16" height="16" />
              </template>
            </a-input>
          </span>

          <span class="table-search-box">
            创建日期：
            <a-range-picker v-model:value="selectValue" :valueFormat="'YYYY-MM-DD'" />
          </span>
        </div>
        <div class="table-search-btn">
          <a-button class="actionBtn" type="primary" ghost @click="tableRef.refresh(true)">
            <SvgIcon class="iconDef" :name="'search'" :color="'#2590FF'" width="16" height="16" />
            查询
          </a-button>

          <a-button class="actionBtn" type="primary" ghost @click="refreshTable">
            <SvgIcon class="iconDef" :name="'refresh'" :color="'#2590FF'" width="16" height="16" />
            重置
          </a-button>
        </div>
      </div>
      <div style="margin-top: 16px">
        <a-button type="primary" @click="addSpace">
          <PlusOutlined />
          新增交付空间
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="handelDetial(record)">详情</a>
          <a @click="editSpace(record)">编辑</a>
          <a @click="deleteSpace(record)">删除</a>
        </div>
      </template>
    </template>
  </Table>

  <BasicModal
    ref="addSpaceModal"
    :title="`${ModalName[modelType]}交付空间`"
    width="1000px"
    :confirmLoading="editDeliverySpaceLoading"
    @emit-callback-fn="addCallbackFn($event)"
  >
    <template #content>
      <a-form
        ref="formRef"
        name="advanced_search"
        label-align="right"
        class="ant-advanced-search-form"
        :model="formState"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              label="项目编号"
              name="projectCode"
              :rules="[
                { required: true, message: '请输入项目编号' },
                {
                  pattern: /^(?!-)[a-z0-9-]{1,50}(?<!-)$/,
                  message: '长度不大于50，只能是小写字母、数字或中划线，且不能以中划线开头或结尾',
                },
              ]"
            >
              <a-input
                v-model:value="formState.projectCode"
                placeholder="请输入项目编号"
                :disabled="detailFlaf"
                allowClear
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="空间名称" name="name" :rules="[{ required: true, message: '请输入空间名称' }]">
              <a-input v-model:value="formState.name" placeholder="请输入空间名称" :disabled="detailFlaf" allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="空间编码" name="code" :rules="[{ required: true, message: '请输入空间编码' }]">
              <a-input
                v-model:value="formState.code"
                placeholder="请输入空间编码"
                :disabled="modelType === ModalType.edit || detailFlaf"
                allowClear
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item label="别名">
              <a-input v-model:value="formState.alias" placeholder="请输入别名" :disabled="detailFlaf" allowClear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="目标集群" name="clusterUuid" :rules="[{ required: true, message: '请选择目标集群' }]">
              <a-select
                v-model:value="formState.clusterUuid"
                @change="handelCluster"
                :options="clusterList"
                placeholder="请选择目标集群"
                :fieldNames="{ label: 'name', value: 'uuid' }"
                :disabled="detailFlaf"
              >
                <template #suffixIcon>
                  <CaretDownOutlined style="color: #6b84a5" />
                </template>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <template v-for="(item, index) in formState.namespace" :key="index">
            <a-col :span="24" class="row-item">
              <a-form-item
                :class="{ 'ant-form-item-with-xx': index > 0 }"
                :label="index === 0 ? '命名空间' : '    '"
                :key="index"
                :name="['namespace', index, 'value']"
                :rules="[{ required: true, message: '请选择命名空间' }]"
              >
                <a-select
                  v-model:value="item.value"
                  :options="spaceList"
                  :disabled="detailFlaf"
                  placeholder="请选择命名空间"
                  :fieldNames="{ label: 'namespaceName', value: 'namespaceName' }"
                >
                  <template #suffixIcon>
                    <CaretDownOutlined style="color: #6b84a5" />
                  </template>
                </a-select>
              </a-form-item>
              <div class="row-icon" v-if="formState.clusterUuid && [ModalType.edit, ModalType.add].includes(modelType)">
                <PlusCircleFilled v-if="index === 0" @click="addNamespace" />
                <MinusCircleOutlined v-else style="color: #ff4d4f" @click="formState.namespace.splice(index, 1)" />
              </div>
            </a-col>
          </template>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item label="备注">
              <a-textarea v-model:value="formState.remark" placeholder="请输入备注" :disabled="detailFlaf" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
  </BasicModal>

  <a-modal
    v-model:visible="visible"
    title="创建命名空间"
    :keyboard="false"
    :maskClosable="false"
    destroyOnClose
    centered
    :confirmLoading="editSpaceLoading"
    @ok="addNamespaceData"
  >
    <a-form ref="formNamespaceRef" label-align="right" :model="formName">
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item label="命名空间" name="formNamespace" :rules="rulesFun">
            <a-input v-model:value="formName.formNamespace" placeholder="请输入命名空间" allowClear />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {
  PlusOutlined,
  PlusCircleFilled,
  MinusCircleOutlined,
  CaretDownOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue';
import {
  querSpacePageListFun,
  addSpaceDataFun,
  putSpaceDataFun,
  deleteSpaceDataFun,
  queryClusterAllList,
  querAllNameSpace,
  addNamespaceFun,
  getExistsEnvironmentLimit,
} from '@/api/operationManagement';
import { Modal, message } from 'ant-design-vue';
import { createVNode } from 'vue';
import { validatorCode } from '@/settings/commonSettings';
import { ModalName, ModalType } from '@/enums/commonEnum';
const searchValue = ref<any>('');
const selectValue = ref<any>([]);

const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'name', title: '空间名称', align: 'center', ellipsis: true },
  { dataIndex: 'code', title: '空间编码', align: 'center', ellipsis: true },
  { dataIndex: 'alias', title: '别名', align: 'center', ellipsis: true },
  { dataIndex: 'namespace', title: '命名空间', align: 'center', ellipsis: true },
  { dataIndex: 'clusterName', title: '目标集群', align: 'center', ellipsis: true },
  { dataIndex: 'remark', title: '备注', align: 'center', width: 240, ellipsis: true },
  { dataIndex: 'creator', title: '创建人', align: 'center', ellipsis: true },
  { dataIndex: 'createTime', title: '创建时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];

const tableRef = ref<any>('');
const detailFlaf = ref<boolean>(false);

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      condition: searchValue.value,
      startDate: selectValue.value && selectValue.value[0],
      endDate: selectValue.value && selectValue.value[1],
    },
  };
  const data = await getList(parameObj);
  return data;
};

//获取表格数据
const getList = async (parameObj: any) => {
  return await querSpacePageListFun(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res.records,
    };
    return data;
  });
};

//刷新表格数据
const refreshTable = () => {
  searchValue.value = '';
  detailFlaf.value = false;
  selectValue.value = undefined;
  tableRef.value.refresh(true);
};

const addSpaceModal = ref<any>(null);
const modelType = ref<ModalType>(ModalType.add);
const formRef = ref<any>(null);
const formState = reactive<any>({
  name: '',
  code: '',
  alias: '',
  clusterUuid: null,
  namespace: [{ name: '命名空间', value: null }],
  remark: '',
  projectCode: '',
});
const spaceList = ref<any[]>([]);
const clusterList = ref<any[]>([]);

onMounted(() => {
  getClusterList();
});

//获取目标集群
const getClusterList = async () => {
  return await queryClusterAllList().then((res) => {
    clusterList.value = res;
  });
};

//目标集群切换 获取命名空间
const handelCluster = async (val: any) => {
  await querAllNameSpace({ targetClusterUuid: val }).then((res) => {
    spaceList.value = res;
  });
};

const visible = ref<boolean>(false);
const formNamespaceRef = ref<any>(null);
const formName = reactive<any>({
  formNamespace: '',
});

const rulesFun = [
  {
    required: true,
    validator: (rule: any, value: any, callback: any) => {
      if (value) {
        if (!validatorCode.test(value)) {
          callback('请输入长度不超过50字符的小写字母、数字或中划线，且不能以中划线开头或结尾。');
        } else {
          callback();
        }
      } else {
        callback('命名空间不能为空');
      }
    },
  },
];

//弹出命名空间
const addNamespace = () => {
  visible.value = true;
};

//添加命名空间
const editSpaceLoading = ref<boolean>(false);
const addNamespaceData = async () => {
  formNamespaceRef.value
    .validate()
    .then(async () => {
      editSpaceLoading.value = true;
      const { formNamespace } = toRaw(formName);
      let parameObj: any = {
        namespaceName: formNamespace,
        targetClusterUuid: formState.clusterUuid,
      };
      await addNamespaceFun(parameObj)
        .then(() => {
          handelCluster(formState.clusterUuid);
          message.success('添加成功');
          visible.value = false;
        })
        .finally(() => {
          editSpaceLoading.value = false;
        });
    })
    .catch((err: any) => {
      console.log('error', err);
    });
};

//添加交付空间
const addSpace = () => {
  restForm();
  detailFlaf.value = false;
  modelType.value = ModalType.add;
  // 新增交付空间给项目编号默认值
  formState.projectCode = 'sh-project-001';
  addSpaceModal.value.showModal();
};

//表格详情
const handelDetial = async (record: any) => {
  restForm();
  await handelCluster(record.clusterUuid);
  detailFlaf.value = true;
  modelType.value = ModalType.detail;
  formState.name = record.name;
  formState.code = record.code;
  formState.alias = record.alias;
  formState.clusterUuid = record.clusterUuid;
  formState.namespace = [{ name: '命名空间', value: record.namespace }];
  formState.remark = record.remark;
  formState.projectCode = record.projectCode;
  addSpaceModal.value.showModal(record, '关闭');
};

//编辑交付空间
const editSpace = async (record: any) => {
  restForm();
  await handelCluster(record.clusterUuid);
  detailFlaf.value = false;
  modelType.value = ModalType.edit;
  addSpaceModal.value.showModal(record);
  formState.name = record.name;
  formState.code = record.code;
  formState.alias = record.alias;
  formState.clusterUuid = record.clusterUuid;
  formState.namespace = [{ name: '命名空间', value: record.namespace }];
  formState.remark = record.remark;
  formState.projectCode = record.projectCode;
};

const editDeliverySpaceLoading = ref<boolean>(false);
const addCallbackFn = async (obj: any) => {
  formRef.value
    .validate()
    .then(async () => {
      editDeliverySpaceLoading.value = true;
      const { alias, clusterUuid, name, code, namespace, remark, projectCode } = toRaw(formState);
      let parameObj: any = {
        alias,
        clusterUuid,
        name,
        code,
        namespace: namespace[0].value,
        remark,
        projectCode,
      };
      if (modelType.value === ModalType.add) {
        await addSpaceDataFun(parameObj)
          .then(() => {
            message.success('添加成功');
            tableRef.value.refresh(true);
            addSpaceModal.value.hideModal();
          })
          .finally(() => {
            editDeliverySpaceLoading.value = false;
          });
      }

      if (modelType.value === ModalType.edit) {
        parameObj = {
          ...parameObj,
          uuid: obj.propsData.uuid,
        };
        await putSpaceDataFun(parameObj)
          .then(() => {
            message.success('编辑成功');
            tableRef.value.refresh(true);
            addSpaceModal.value.hideModal();
          })
          .finally(() => {
            editDeliverySpaceLoading.value = false;
          });
      }
    })
    .catch((err: any) => {
      console.log('error', err);
    });
};

//删除交付空间
const deleteSpace = async (record: any) => {
  await getExistsEnvironmentLimit(record.uuid).then((res: any) => {
    // data返回true代表有限制，false调用删除接口
    if (!res) {
      deleteSpaceData(record);
    } else {
      Modal.confirm({
        title: '您还不能删除该交付空间！',
        icon: createVNode(ExclamationCircleOutlined),
        content: '该交付空间已绑定环境，请解绑后再尝试删除！',
        centered: true,
        okText: '确定',
        cancelText: '取消',
      });
    }
  });
};

const deleteSpaceData = async (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode('div', { style: 'color:black;' }, `确定要删除“交付空间：${record.name}”这一项数据吗？`),
    async onOk() {
      await deleteSpaceDataFun(record.uuid).then(() => {
        message.success('删除成功');
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
  });
};

const restForm = () => {
  formState.name = '';
  formState.code = '';
  formState.alias = '';
  formState.clusterUuid = null;
  formState.namespace = [{ name: '命名空间', value: null }];
  formState.remark = '';
  formState.projectCode = '';
};
</script>

<style scoped lang="less">
.table-search {
  border-bottom: 1px solid #e7eff8;
  padding-bottom: 16px;
}

.ant-advanced-search-form {
  padding-right: 36px;
  :deep(.ant-form-item-label) {
    width: 100px;
  }

  .row-item {
    position: relative;
    .row-icon {
      position: absolute;
      right: -20px;
      top: 3px;
      cursor: pointer;
      color: #2590ff;
      font-size: 16px;
    }
  }

  .ant-form-item-with-xx {
    :deep(.ant-form-item-label) {
      label {
        display: none !important;
      }
    }
  }
}
</style>
